package iu.gq.template;

import iu.gq.db.DatabaseHelper;
import iu.gq.db.DbAdapter;
import iu.gq.db.items.ChapterItem;
import java.util.ArrayList;
import java.util.List;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdView;
import com.gq.utils.SharePreferenceUtil;
import com.gq.widget.actionbar.ActionBarActivity;

public class ChapterActivity extends ActionBarActivity implements OnTouchListener {

	private ListView listView;
	private TextView chapterNotification;
	private List<ChapterItem> mChapterList = new ArrayList<ChapterItem>();
	private AdView adView;
	private Handler mHandler;
	private ProgressDialog mProgressDlg;
	
	private void setListAdapter(final Runnable run) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				mChapterList = new DbAdapter(ChapterActivity.this).getAllChapterItems();
				runOnUiThread(run);
			}
		}).start();
	}
	
	private Runnable loadAdsRun = new Runnable() {
		
		@Override
		public void run() {
			if (adView != null) {
				adView.stopLoading();
				adView.loadAd(new AdRequest());
			}
		}
	};
	
	public void checkDBVersion() {
		int newVersion = GQConst.DBVERSION;
		SharePreferenceUtil sharepreference = SharePreferenceUtil.getInstance(ChapterActivity.this); 
		int currentVersion = sharepreference.getDbVersion();
		if (currentVersion < newVersion) {
			getBaseContext().deleteDatabase(DatabaseHelper.DBNAME);
			sharepreference.setDbVersion(newVersion);
		} 
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chapter_scr);
		mProgressDlg = ProgressDialog.show(ChapterActivity.this, "", "Đang tải dữ liệu, vui lòng chờ !", true);
		checkDBVersion();						// check db version here to update new data when re-install app or update app from google play
		mHandler = new Handler();
		listView = (ListView) findViewById(R.id.chapterlist);
		if (!GQConst.FINISHED) {
			ViewGroup vgr = (ViewGroup) ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.item_list_footer, null, false);
			listView.addFooterView(vgr);
		}
		chapterNotification = (TextView) findViewById(R.id.tvnotification);
		chapterNotification.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				chapterNotification.setVisibility(View.GONE);
				SharePreferenceUtil.getInstance(ChapterActivity.this).removeNotification();
				final ChapterItem readingChapter = SharePreferenceUtil.getInstance(ChapterActivity.this).getLastChapter();
				int position = (readingChapter == null) ? 0 : readingChapter.getPosition();
				ReaderActivity.startReaderActivity(ChapterActivity.this, null, position);
			}
		});
		
		setListAdapter(new Runnable() {
			
			@Override
			public void run() {
				listView.setAdapter(new ChapterItemAdapter(ChapterActivity.this, R.id.text_view, mChapterList));
				if (mProgressDlg != null) {
					if (mProgressDlg.isShowing()) mProgressDlg.cancel();
				}
			}
		});
		listView.setAdapter(new ChapterItemAdapter(this, R.id.text_view, mChapterList));
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				if (id != -1) {
					ReaderActivity.startReaderActivity(ChapterActivity.this, (ArrayList<? extends Parcelable>) mChapterList, position);
				}
			}
		});
		adView = (AdView) findViewById(R.id.adView);
		adView.setAdListener(new AdListener() {
			
			@Override
			public void onReceiveAd(Ad ad) {
				mHandler.removeCallbacks(loadAdsRun);
				mHandler.postDelayed(loadAdsRun, 60000);
			}
			
			@Override
			public void onPresentScreen(Ad ad) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onLeaveApplication(Ad ad) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onFailedToReceiveAd(Ad ad, ErrorCode e) {
				mHandler.removeCallbacks(loadAdsRun);
				mHandler.postDelayed(loadAdsRun, 10000);
			}
			
			@Override
			public void onDismissScreen(Ad ad) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		final ChapterItem readingChapter = SharePreferenceUtil.getInstance(ChapterActivity.this).getLastChapter();
		if (SharePreferenceUtil.getInstance(this).getLastChapter() != null && SharePreferenceUtil.getInstance(this).isShowNotification()) {
			chapterNotification.setVisibility(View.VISIBLE);
			chapterNotification.setText("Bạn đang đọc \""+readingChapter.getTitle()+"\"");
		} else {
			chapterNotification.setVisibility(View.GONE);
		}
		adView.loadAd(new AdRequest());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater mMenuInflater = getMenuInflater();
		mMenuInflater.inflate(R.menu.index, menu);
		getActionBarHelper().setDisplayHomeAsUpEnabled(true);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
			case android.R.id.home:
				onBackPressed();
				break;
			case R.id.menu_info:
				try {
					startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(GQConst.SEARCHURI)));
				} catch (ActivityNotFoundException e) {
					Toast.makeText(ChapterActivity.this, "Không có ứng dụng Google Play trong máy", Toast.LENGTH_SHORT).show();
				}
				break;
			case R.id.menu_openbook:
				ChapterItem reading = SharePreferenceUtil.getInstance(ChapterActivity.this).getLastChapter();
				if (reading != null) {
					ReaderActivity.startReaderActivity(ChapterActivity.this, null, reading.getPosition());
					if (SharePreferenceUtil.getInstance(ChapterActivity.this).isShowNotification()) {
						SharePreferenceUtil.getInstance(ChapterActivity.this).removeNotification();
						chapterNotification.setVisibility(View.GONE);
					}
				} else {
					Toast.makeText(ChapterActivity.this, "Bạn chưa nhớ chương nào !", Toast.LENGTH_SHORT).show();
				}
				break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private class ChapterItemAdapter extends ArrayAdapter<ChapterItem> {

		private Context context;
		private List<ChapterItem> mChapterItems;
		
		public ChapterItemAdapter(Context context, int textViewResourceId,
				List<ChapterItem> objects) {
			super(context, textViewResourceId, objects);
			this.context = context;
			this.mChapterItems = objects;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = ((LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.item_list, null, false);
			}
			ChapterItem item = this.mChapterItems.get(position);
			((TextView) convertView.findViewById(R.id.text_view)).setText(item.getTitle());
			convertView.setTag(item);
			return convertView;
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		return false;
	}

	@Override
	protected void onStop() {
		if (adView != null) {
			mHandler.removeCallbacks(loadAdsRun);
			adView.stopLoading();
		}
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		if (mProgressDlg != null) mProgressDlg.cancel();
		if (adView != null) adView.destroy();
		super.onDestroy();
	}
}
